<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/14
 * Time: 15:57
 */

namespace app\api\controller;

use app\admin\controller\BaseAdminController;
use app\api\model\GoodsRule;
use app\api\model\OrderDetail;
use app\api\validate\OrderValidate;
use app\api\model\Cart;
use app\api\model\Order as OrderModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;

class Order extends BaseAdminController
{

    /**
     * 列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = request()->param();
        validate(OrderValidate::class)->scene('list')->check($param);
        $model = new OrderModel();
        $model = $model->withSearch('no', $param);
        $model = $model->where('user_id', $this->user_id);
        $count = $model->count();
        $model = $model->page($param['page'], $param['limit']);
        $list  = $model->with(['orderDetail'])->order($this->orderSort)->select()->each(function ($item) {
            $item->imgs        = $item->orderDetail->column('img');//图片数组
            $item->total_price = $item->orderDetail()->sum('amount');//总金额
            $item->total_num   = $item->orderDetail()->sum('quantity');//总数量
            $item->total_kind  = $item->orderDetail->count();//种类
            unset($item->orderDetail);
        });
        return $this->success('请求成功', compact('count', 'list'));
    }

    /**
     * 生成订单
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function add(): Response
    {
        $param = request()->param();
        validate(OrderValidate::class)->scene('add')->check($param);

        $carts = Cart::whereIn('id', $param['cart_ids'])->select();
        if ($carts->isEmpty()) return $this->error('购物车为空');
        $model = new OrderModel();
        $model->startTrans();
        try {
            //生成订单
            $param['user_id'] = $this->user_id;
            $order            = OrderModel::create($param);
            if ($order->id) $this->error('添加失败');
            //添加明细
            $carts->each(function ($item) use ($order) {
                $goodsRule = GoodsRule::where('id', $item->goods_rule_id)->find();
                if (!$goodsRule) exception('商品不存在');
                if($goodsRule->quantity < $item->quantity) exception('库存不足');
                GoodsRule::where('id', $item->goods_rule_id)->Dec('quantity',$item->quantity)->update();//扣减库存
                //
                unset($item->id, $item->create_time, $item->update_time, $item->delete_time, $item->status);
                $item->order_id = $order->id;
            });
            (new OrderDetail())->saveAll($carts->toArray());
            //删除购物车
            $ids = explode(',', $param['cart_ids']);
            if (!Cart::destroy($ids)) exception('删除购物车失败');
            $model->commit();
        } catch (\Exception $e) {
            $model->rollback();
            return $this->error($e->getMessage());
        }
        return $this->success('订单生成成功');
    }

    /**
     * 订单明细
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail(): Response
    {
        $param = request()->param();
        validate(OrderValidate::class)->scene('detail')->check($param);

        $order              = OrderModel::with(['orderDetail', 'user'])->where('id', $param['id'])->find();
        $order->imgs        = $order->orderDetail->column('img');
        $order->total_price = $order->orderDetail()->sum('amount');//总金额
        $order->total_num   = $order->orderDetail()->sum('quantity');//总数量
        $order->total_kind  = $order->orderDetail->count();//种类
        $order->orderDetail->each(function ($item) {
            $item->name = $item->goods()->value('name') . ' ' . $item->goodsRule()->value('spec_name');
        })->visible(['id', 'img', 'amount', 'quantity','name']);
        $order->user->visible(['id', 'real_name', 'mobile', 'address']);
        return $this->success('请求成功', $order);
    }


}